package com.xsd.awen.web;

import com.xsd.awen.config.WebResult;
import com.xsd.awen.domain.entity.User;
import com.xsd.awen.domain.po.LoginPo;
import com.xsd.awen.domain.vo.LoginVo;
import com.xsd.awen.domain.vo.UserVo;
import com.xsd.awen.service.UserService;
import com.xsd.awen.shiro.CloudAdminToken;
import com.xsd.awen.utils.AES256;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("login")
    public String login(LoginVo loginVo, HttpServletRequest request){
        request.getSession().invalidate();
        request.getSession().setMaxInactiveInterval(28800);
        // 添加用户认证信息
        String password = AES256.encrypt(loginVo.getB());
        loginVo.setB(null);
        CloudAdminToken cloudAdminToken = new CloudAdminToken(loginVo.getA(), password);
        // 进行验证，这里可以捕获异常，然后返回对应信息
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(cloudAdminToken);
        }catch (Throwable e){
            WebResult.ERROR(e.getMessage());
        }
        //response.setHeader(AdminWebSessionManager.LOGIN_TOKEN_KEY,String.valueOf(SecurityUtils.getSubject().getSession().getId()));
        LoginPo loginPo = (LoginPo) subject.getPrincipal();
        return WebResult.OK(loginPo);
    }

    @PostMapping("logout2")
    public String logout2(HttpServletRequest request){
        SecurityUtils.getSubject().logout();
        request.getSession().invalidate();
        return WebResult.OK();
    }

    @PostMapping("page")
    public String page(UserVo userVo){
        return WebResult.page(userService.page(userVo));
    }

    @PostMapping("add")
    public String add(User user){
        return userService.save(user);
    }

    @PostMapping("update")
    public String update(User user){
        return userService.update(user);
    }

    @PostMapping("delete")
    public String delete(User user){
        return userService.delete(user);
    }

    @PostMapping("get")
    public String get(User user){
        return WebResult.OK(userService.getById(user.getId()));
    }

}